import { getFileType, createObjectURL } from '@/common/plugins/tools/file'
import { stringFileName } from '@vimi/utils-tool'

const enumFileIcon = {
  txt: 'fa-file-text-o',
  pdf: 'fa-file-pdf-o',
  mp3: 'fa-file-audio-o',
  mp4: 'fa-file-video-o',
  MP4: 'fa-file-video-o',
  MP3: 'fa-file-video-o',
  mov: 'fa-file-video-o',
  flv: 'fa-file-video-o',
  zip: 'fa-file-archive-o',
  rar: 'fa-file-archive-o',
  jar: 'fa-file-archive-o',
  xls: 'fa-file-excel-o',
  xlsx: 'fa-file-excel-o',
  doc: 'fa-file-word-o',
  docx: 'fa-file-word-o',
  ppt: 'fa-file-powerpoint-o',
  pptx: 'fa-file-powerpoint-o',
  jpeg: 'fa-file-image-o',
  jpg: 'fa-file-image-o',
  png: 'fa-file-image-o',
  gif: 'fa-file-image-o',
}
const defaultFileIcon = 'fa-file-o'

const getType = fileType => {
  // 图片类型
  if (/(jpe?g|png|gif|bmp|webp)/i.test(fileType)) return 'image'

  // 可直接打开类型
  if (/(txt|pdf|mp3|mp4)/i.test(fileType)) return 'link'

  // office 在线预览
  if (/(pptx?|docx?|xlsx?)/.test(fileType)) return 'office'

  return 'file'
}

/**
 * 根据文件后缀，获取文件查看类型
 * @param {*} fileType 文件后缀
 * @returns type image | link | file
 */
export const getViewType = fileType => {
  const icon = enumFileIcon[fileType] || defaultFileIcon
  const type = getType(fileType)
  return { type, icon }
}

export const attachAdapter = attach => {
  const name = attach.remark || stringFileName(attach.attachment ?? '未知附件')
  const fileType = getFileType(name)
  const { type: viewType, icon: viewIcon } = getViewType(fileType)
  return {
    ...attach,
    name,
    fileType,
    viewType,
    viewIcon,
    url: attach.attachment,
  }
}

export const fileAdapter = file => {
  const { name, size = 0 } = file
  const fileType = getFileType(name)
  const { type: viewType, icon: viewIcon } = getViewType(fileType)
  const url = createObjectURL(file)
  return {
    file,
    size,
    name,
    fileType,
    viewType,
    viewIcon,
    url,
    percent: 0,
    loading: false,
  }
}
